from datetime import timedelta
from fastapi import APIRouter, Depends
from fastapi.security.oauth2 import OAuth2PasswordRequestForm
from sqlalchemy.orm.session import Session

from .dependencies import ACCESS_TOKEN_EXPIRE_MINUTES, authenticate_user, create_access_token, get_db

from . import models
from .database import engine

from .APIs import classes, users


models.Base.metadata.create_all(bind=engine)

router = APIRouter(
    prefix='/sql',
    tags=['数据库']
)

router.include_router(classes.router)
router.include_router(users.router)

@router.get('/')
def test():
    return {
        'message': 'This is the main frame of sql'
    }

# 注：OAuth2PasswordRequestForm可变更为其他的Form
@router.post('/token')
async def login_for_access_token(form_data: OAuth2PasswordRequestForm=Depends(), db: Session=Depends(get_db)):
    user = authenticate_user(form_data.username, form_data.password, db)
    if not user:
        return {
            'code': 1,
            'message': '登陆失败'
        }
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={'sub': user.number}, expires_delta=access_token_expires
    )
    return {
        'code': 0,
        'message': '登陆成功',
        'access_token': access_token,
        'token_type': 'bearer'
    }